package com.sprocomm.agingtest;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sprocomm.agingtest.Video.VideoActivity;
import com.sprocomm.agingtest.camera.FlashTest;
import com.sprocomm.agingtest.camera.VedioTest3;
import com.sprocomm.agingtest.ir.IRTestActivity;
import com.sprocomm.agingtest.mic.MicTestActivity;
import com.sprocomm.agingtest.reboot.RebootTest;
import com.sprocomm.agingtest.vibrator.VibratorTest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    private static String TAG = "MainActivity";
    private Context mContext;
    private ListView listView;
    private ListAdapter listAdapter;
    private SharedPreferences mSharedPreferences;

    private List<Map<String, Object>> list;
    private String[] mStrings = new String[]{
            "Vibrator",
            "Flash",
            "SoundUnit",
            "VideoRecord",
            "Reboot",
            "VideoPlay",
            "MIC",
            "IR"
    };
    private int pass = 1;
    private int fail = -1;
    private int normal = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSharedPreferences = getSharedPreferences("main", MODE_PRIVATE);
        //设置屏幕最大亮度
        Tools.setScreenBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_FULL, this);

        listView = (ListView) findViewById(R.id.lv_main);
        initData();
        listAdapter = new ListAdapter();
        listView.setAdapter(listAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String text = list.get(i).get("name").toString();
                Tools.logE("click:" + text);
                switch (text) {
                    case "Vibrator":
                        Intent intent = new Intent(MainActivity.this, VibratorTest.class);
                        startActivityForResult(intent, 0x001);
                        break;
                    case "Flash":
                        Intent intent2 = new Intent(MainActivity.this, FlashTest.class);
                        startActivityForResult(intent2, 0x003);
                        break;
                    case "SoundUnit":
                        //添加喇叭
                        final CharSequence[] units = new CharSequence[]{"Receiver","Speaker"};
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Please select the sounding unit")
                                .setItems(units, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        String unit = (String) units[which];
                                        Intent intent3 = new Intent();
                                        intent3.putExtra("SoundUnit",unit);
                                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                                            intent3.setAction("receivertest2");
                                        } else {
                                            intent3.setAction("receivertest");
                                        }
                                        startActivityForResult(intent3, 0x005);
                                    }
                                }).create().show();

                        //Toast.makeText(getApplicationContext(),Build.VERSION.SDK_INT+":",Toast.LENGTH_SHORT).show();

                        break;
                    case "VideoRecord":
                        Intent intent4 = new Intent(MainActivity.this, VedioTest3.class);
                        startActivityForResult(intent4, 0x007);
                        break;
                    case "Reboot":
                        Intent intent5 = new Intent(MainActivity.this, RebootTest.class);
                        intent5.putExtra("isManual", true);
                        startActivityForResult(intent5, 0x009);
                        break;
                    case "VideoPlay":
                        int connType = Tools.getConnectyType(getApplicationContext());
                        if (connType == ConnectivityManager.TYPE_WIFI) {
                            Intent intent6 = new Intent(MainActivity.this, VideoActivity.class);
                            startActivityForResult(intent6, 0x011);
                        } else {
                            Snackbar.make(listView, "WiFi has no connection", Snackbar.LENGTH_LONG)
                                    .setAction("go setting", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            //go setting
                                            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                                        }
                                    }).show();
                        }
                        break;
                    case "MIC":
                        Intent intent7 = new Intent(MainActivity.this, MicTestActivity.class);
                        startActivityForResult(intent7, 0x013);
                        break;
                    case "IR":
                        Intent intent9 = new Intent(MainActivity.this, IRTestActivity.class);
                        startActivityForResult(intent9, 0x015);
                        break;
                    default:
                        break;
                }
            }
        });
        getPermission();
    }

    /**
     * 检查权限
     */
    private void getPermission() {
//        String[] permissions = new String[]{
//                Manifest.permission.CAMERA,
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.RECORD_AUDIO
//        };
        //动态权限申请
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.DISABLE_KEYGUARD) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.REBOOT) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.DISABLE_KEYGUARD,
                    Manifest.permission.REBOOT,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.ACCESS_WIFI_STATE}, 0x001);
            return;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 0 表示有权限-1表示没有权限
        if (requestCode == 0x001) {
            Tools.logE("permissions:" + permissions.toString() + "grantResults" + grantResults.toString());
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        list = new ArrayList<>();
        for (int i = 0; i < mStrings.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("status", mSharedPreferences.getInt(mStrings[i], 0));
            map.put("name", mStrings[i]);
            list.add(map);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            boolean result = data.getBooleanExtra("result", false);
            int stauts;
            int index = 0;
            if (result) {
                stauts = pass;
            } else {
                stauts = fail;
            }
            if (mSharedPreferences == null) {
                mSharedPreferences = this.getSharedPreferences("main", MODE_PRIVATE);
            }
            Tools.logE(result + "");
            if (requestCode == 0x001) {
                index = 0;
            } else if (requestCode == 0x003) {
                index = 1;
            } else if (requestCode == 0x005) {
                index = 2;
            } else if (requestCode == 0x007) {
                index = 3;
            } else if (requestCode == 0x009) {
                index = 4;
            } else if (requestCode == 0x011) {
                index = 5;
            }else if(requestCode == 0x013){
                index = 6;
            }else if(requestCode == 0x015){
                index = 7;
            }
            list.get(index).put("status", stauts);
            mSharedPreferences.edit().putInt(mStrings[index], stauts).commit();
            listAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Tools.setScreenBrightness(WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE, this);
    }

    public class ListAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View root = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item, null);
            TextView textView = (TextView) root.findViewById(R.id.tv_item);
            textView.setText(list.get(i).get("name").toString());
            //textView.setBackgroundColor((Integer) list.get(i).get("status"));
            int bg = (int) list.get(i).get("status");
            Tools.logE("bg:" + bg);
            if (bg == pass) {
                textView.setBackgroundResource(R.drawable.list_bg_green);
            } else if (bg == fail) {
                textView.setBackgroundResource(R.drawable.list_bg_red);
            } else {
                textView.setBackgroundResource(R.drawable.list_bg_white);
            }
            return root;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_clean) {
            new AlertDialog.Builder(this)
                    .setTitle("Clean Test?")
                    .setNegativeButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            mSharedPreferences.edit().clear().commit();
                            initData();
                            listAdapter.notifyDataSetChanged();
                        }
                    })
                    .setPositiveButton("NO", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .create().show();

        } else if (id == R.id.menu_about) {
            new AlertDialog.Builder(this)
                    .setTitle("About")
                    .setMessage("Powered by Sprocomm")
                    .create().show();
        }
        return true;
    }
}
